import { Spin, Upload } from 'antd';
import ModalUtil from '@/utils/modal.js';
import { ResourceApi } from '@/api/resource/api.js';
import { useState } from 'react';
import { useUpdateEffect } from 'ahooks';

/**
 * 文件上传组件
 *
 * @param props {Object} 组件属性
 * @param props.render {Function} 子组件
 * @param props.onSuccess {Function} 上传成功回调函数
 * @param props.pId {String} 上传文件所属的父级资源ID
 * @param props.path {String} 上传文件所属的路径
 * @param props.onLoading {Function} 上传中回调函数
 */
export default function FileUpload(props) {
  const { render, pId, path, onLoading } = props;
  const [loading, setLoading] = useState(false);

  useUpdateEffect(() => {
    onLoading && onLoading(loading);
  }, [loading]);

  const uploadProps = {
    maxCount: 1,
    showUploadList: false,
    customRequest: async (params) => {
      setLoading(true);
      const { onSuccess, onError, file } = params;
      const { code, data } = await ResourceApi.upload(file, pId ?? 0, path);
      if (code === 0) {
        onSuccess(data);
      } else {
        onError();
      }
      setLoading(false);
    },
    onChange(info) {
      if (info.file.status === 'done') {
        const encryptionId = info?.file?.response?.encryptionId;
        const url = `/v/${encryptionId}`;
        props?.onSuccess && props.onSuccess(url);
        ModalUtil.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        ModalUtil.error(`${info.file.name} 文件上传失败`);
      }
    }
  };

  if (loading) {
    return <Spin spinning={true}>{render && render()}</Spin>;
  }

  return <Upload {...uploadProps}>{render && render()}</Upload>;
}
